package com.caocaog.market.finance.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.constant.MarketConstant;
import com.caocaog.market.finance.entity.MkBillBase;
import com.caocaog.market.finance.entity.MkBillHistory;
import com.caocaog.market.finance.mapper.MkBillBaseMapper;
import com.caocaog.market.finance.mapper.MkBillHistoryMapper;
import com.caocaog.market.finance.service.MkBillBaseService;
import com.caocaog.market.finance.service.MkBillHistoryService;
import net.sf.saxon.value.StringValue;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.SystemException;
import javax.transaction.Transactional;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author liguang
 * @version 1.0.0
 * @Project jeecg-boot
 * @Package com.caocaog.market.finance.service.impl
 * @ClassName MkBillHistoryServiceImpl.java
 * @createTime 2021年12月03日 19:25:00
 * @Description TODO
 */
@Service
public class MkBillHistoryServiceImpl implements MkBillHistoryService {
    @Autowired
    private MkBillHistoryMapper billHistoryMapper;

    @Override
    @Transactional(rollbackOn = SystemException.class)
    public int insertBillAndHistory(MkBillHistory billHistory) {

//        添加测试时需要把这个注释
        MkBillBase billBase = new MkBillBase();
        String billHistoryId = IdWorker.getIdStr(billHistory);
        String billBaseId = IdWorker.getIdStr(billBase);
        /**
         * 生成MkBillHistory中的id值
         */
        billHistory.setId(billHistoryId);
        /**
         * 生成MkBillBase中的id值
         */
        billHistory.setBillBaseId(billBaseId);
        if (null == billHistory.getCreateBy()) {
            LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            billHistory.setCreateBy(loginUser.getUsername());
        }

        // 待结算
        billHistory.setPayStatus(MarketConstant.FINANCE_PAY_STATUS_DJS);
        // 正常付款
        billHistory.setPayStatusChangeReason(MarketConstant.FINANCE_PAY_STATUS_CHANGE_REASON_ZCFK);
        billHistory.setCreateTime(new Date());

        /**以下为测试用的 --（如需手动添加测试数据，把这个注释放开即可）-- 开始 */
//        testInsert(billHistory);
//        return 1;
        /**以上为测试用的 ---- 结束 */
        try {
            //虽然执行两条insert语句，但是这里依然会返回1
            int count = billHistoryMapper.insertBillAndHistory(billHistory);
            if (count < 1) {
                // 插入的不是两条数据，则将刚插入的数据 根据id删除；返回 0
                billHistoryMapper.deleteBillAndHistory(billBaseId, billHistoryId);
                return 0;
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    private void testInsert(MkBillHistory billHistory) {
        String orderNo = billHistory.getOrderNo();
        String serno = billHistory.getPaySerno();
        for (int i = 10; i < 1100; i++) {
            //这个for循环是测试用的
            MkBillBase billBase = new MkBillBase();
            String billHistoryId = IdWorker.getIdStr(billHistory);
            String billBaseId = IdWorker.getIdStr(billBase);
            billHistory.setId(billHistoryId);
            billHistory.setBillBaseId(billBaseId);
            int num = i;
            billHistory.setOrderNo(String.valueOf(i) + orderNo);
            billHistory.setPaySerno(String.valueOf(i) + serno);
            double a = Math.random() * 10;
            DecimalFormat df = new DecimalFormat("0.00");
            billHistory.setPayAmount(df.format(a));
            billHistory.setPayTime(randomDate("2020-12-31", "2021-12-02"));
            int count = billHistoryMapper.insertBillAndHistory(billHistory);
            if (count < 1) {
                // 插入的不是两条数据，则将刚插入的数据 根据id删除；返回 0
                billHistoryMapper.deleteBillAndHistory(billBaseId, billHistoryId);
            }
            System.out.println("插入成功的条数：" + (num - 9) + " 条数据  ");
        }
    }

    private static Date randomDate(String beginDate, String endDate) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date start = format.parse(beginDate);
            Date end = format.parse(endDate);

            if (start.getTime() >= end.getTime()) {
                return null;
            }
            long date = random(start.getTime(), end.getTime());
            return new Date(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static long random(long begin, long end) {
        long rtn = begin + (long) (Math.random() * (end - begin));
        if (rtn == begin || rtn == end) {
            return random(begin, end);
        }
        return rtn;
    }
}
